package com.fangs.kotlin_banner.banner

import android.content.Context
import android.media.MediaPlayer
import android.media.MediaPlayer.OnCompletionListener
import android.media.MediaPlayer.OnPreparedListener
import android.net.Uri
import android.os.Handler
import android.view.View
import com.fangs.kotlin_banner.Apps
import java.lang.Exception

class MyBannerVideoView private constructor(context: Context) :
    TextureVideoView(context) {
    private var url: String? = null
    private var loop //是否循环播放
            = false
    private var showLoadingListener: ShowLoadingListener? = null
    private val mVideoViewHandler = Handler()
    private val runable_play: Runnable = object : Runnable {
        override fun run() {
            if (getCurrentPosition() > 50) { // 避免虽然开始播放但画面未显示仍黑屏情况 故延迟50毫秒消除蒙版
                if (scaleError) {
                    setScale()
                    scaleError = false
                }
                showLoadingListener!!.showLoading(false)
                mVideoViewHandler.removeCallbacks(this)
            } else {
                mVideoViewHandler.postDelayed(this, 100)
            }
        }
    }
    private var mScaleX = 0f
    private var scaleError = false

    constructor(context: Context, loop: Boolean) : this(context) {
        this.loop = loop
        init()
    }

    private fun init() {
        setOnPreparedListener(OnPreparedListener { mp: MediaPlayer ->
            val videoRatio = mp.videoWidth.toFloat() / mp.videoHeight.toFloat()
            val screenRatio = getWidth().toFloat() / getHeight().toFloat()
            mScaleX = videoRatio / screenRatio
            setScale()
            mp.setVolume(0f, 0f)
        })
        setOnCompletionListener(OnCompletionListener { mp: MediaPlayer ->
            if (loop) {
                mp.start()
                mp.isLooping = true
            }
        })
        setOnInfoListener(MediaPlayer.OnInfoListener { mp: MediaPlayer?, what: Int, extra: Int ->
            when (what) {
                MediaPlayer.MEDIA_INFO_BUFFERING_START -> showLoadingListener!!.showBuffering(true)
                MediaPlayer.MEDIA_INFO_BUFFERING_END -> showLoadingListener!!.showBuffering(false)
            }
            true
        })
        setOnErrorListener(MediaPlayer.OnErrorListener { mp: MediaPlayer?, what: Int, extra: Int ->
            showLoading()
            setUrl(url) //播放报错时（有可能是视频缓存被清理）重置播放路径 以便app不退出视频也可重新缓存
            true
        })
    }

    fun setScale() {
        // setScale 为处理视频尺寸不符合banner时 拉伸变形问题
        if (mScaleX >= 1f) {
            setScaleX(mScaleX)
        } else {
            setScaleY(1f / mScaleX)
        }
    }

    fun setScaleError() { // 处理侧滑退出 回到banner页 视频控件内容突然显示不全问题
        if (mScaleX >= 1f) {
            setScaleX(1f)
        } else {
            setScaleY(1f)
        }
        scaleError = true
    }

    fun setUrl(url: String?) {
        try {
            val proxyUrl: String = Apps.proxy?.getProxyUrl(url)!!
            setVideoURI(Uri.parse(proxyUrl))
            if (!Apps.proxy?.isCached(url)!!) {
                Apps.preCacherScreenData(proxyUrl) //开始预加载缓存视频
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        this.url = url
    }

    fun setShowLoadingListener(showLoadingListener: ShowLoadingListener?) {
        this.showLoadingListener = showLoadingListener
    }

    protected override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val width = View.getDefaultSize(getWidth(), widthMeasureSpec)
        val height = View.getDefaultSize(getHeight(), heightMeasureSpec)
        setMeasuredDimension(width, height)
    }

    override fun start() {
        super.start()
        if (showLoadingListener != null) {
            if (getCurrentPosition() < 50) {
                showLoading()
            } else {
                mVideoViewHandler.postDelayed(runable_play, 100)
            }
        }
    }

    private fun showLoading() {
        showLoadingListener!!.showLoading(true)
        mVideoViewHandler.postDelayed(runable_play, 100) //处理 播放前短暂黑屏情况 和 封面到过渡闪屏问题
    }

    interface ShowLoadingListener {
        fun showLoading(show: Boolean)
        fun showBuffering(show: Boolean)
    }
}